<?php

namespace app\admin\validate\dealer;

use app\common\validate\BaseValidate;
use cszchen\citizenid\Parser;

class Dealer extends BaseValidate
{
    /**
     * 验证规则
     */
    protected $rule = [
        'name|姓名'       => 'require|min:2|max:128',
        'mobile|手机号码' => 'require|isMobile',
        'email|电子邮箱' =>'email|unique:admin,email',
        'dealer_type|纳税号' => 'require|checkCanum',
    ];
    /**
     * 提示消息
     */
    protected $message = [
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => ['name', 'mobile', 'email', 'dealer_type'],
        'edit' => ['name', 'mobile', 'dealer_type']
    ];

    protected function checkCanum($value, $rule, $data){
        $dealer_type = $value;
        $data['id'] = input('ids/d', 0);
        if($dealer_type == 1){
            $real = $data['ca_num'];
            if(strlen($real) < 5){
                return '纳税号最少5位';
            }
            //添加 条件之判断 存不存在
            $where['ca_num'] = $real;
            //修该判断排除自身，看下有没有
            if ($data['id'] ?? false) {
                $where['id'] = ['neq', $data['id']];
            }

            if (model('Admin/dealer.Dealer')->where($where)->count() > 0) {
                return '改税号已被使用';
            }
        } else {
            $real = $data['identity_card'];
            $parser = new Parser();
            $parser->setId($real);
            if (!$parser->isValidate()) {
                return '请正确填写身份证号码';
            }

            //添加 条件之判断 存不存在
            $where['identity_card'] = $real;
            //修该判断排除自身，看下有没有
            if ($data['id'] ?? false) {
                $where['id'] = ['neq', $data['id']];
            }

            if (model('Admin/dealer.Dealer')->where($where)->count() > 0) {
                return '身份证已被占用';
            }
        }
        return true;
    }

    protected function checkUnique($value,$rule,$data)
    {
        $ids = input('ids', 0);
        $where = [];
        if ($ids) {
            $where  = ['name'=>$value, 'id' => ['neq', $ids]];
        } else {
            $where = ['name'=>$value];
        }

        $com = \app\admin\model\dealer\Dealer::get($where);

        if ($com) {
            return '经销商名称已经存在';
        }  else {
            return true;
        }
    }
    
}
